package TableEditions;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import TableAdditions.main;
import Utility.DatePicker;
import Utility.Personnel;
import Utility.Vehicle;
import Tables.VehicleTableInterface;

public class VehicleEdition extends JFrame {
	
	
    private JTextField licencePlateField;
    private JTextField kmField;
    private JTextField lastMaintenanceField;
    private JTextField insurenceEndDateField;
    private JTextField nextInspectionField;
    private JComboBox driverIdField;
    Personnel[] personels;
    int driverId2=-1;
    int vehicleDriverIndex=0;
    int newDriverId=0;
    int exDriverId=0;
    
    
	public String km;
	public String driverId="";
	public String licencePlate;
	public String insurenceEndDate;
	public String lastMaintenance;
	public String nextInspection;
	public int vehicleAvailability=1;
	private String selectedDriverName;
	
    private JButton vehicleEditButton;
    VehicleTableInterface cti;
    
    public VehicleEdition(final VehicleTableInterface cti,final Vehicle vehicle) {
		super("Araç Düzenleme Ekranı");
		this.cti = cti;
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setSize(600,200);
		getContentPane().setLayout(null);
		
		exDriverId=vehicle.getVehicleDriverId();
		
		JLabel codeLabel = new JLabel("Plaka");
		codeLabel.setBounds(20, 10, 90, 20);
		getContentPane().add(codeLabel);
		
		licencePlateField = new JTextField();
		licencePlateField.setBounds(157, 11, 130, 20);
		licencePlateField.setText(vehicle.getVehicleLicencePlate());
		getContentPane().add(licencePlateField);
		licencePlateField.setColumns(10);
		
		JLabel authorityLabel = new JLabel("Şoför İsmi");
		authorityLabel.setBounds(20, 40, 90, 20);
		getContentPane().add(authorityLabel);
		
		driverIdField = new JComboBox();
		driverIdField.setBounds(157, 40, 130, 20);
		getContentPane().add(driverIdField);//kmField
		//driverIdField.setColumns(10);
		
		   try {
			    Connection conn = null;
		        Statement stmt = null;
		        ResultSet rss = null;

		        String url = "jdbc:mysql://localhost:3306/mydb";
		        String user = "root";
		        String password = "qweasdzxc";
		        
		        conn = (Connection) DriverManager.getConnection(url, user, password);
				stmt = (Statement) conn.createStatement();
				
				driverIdField.addItem("Personel Adı");
				// TG code updated to use new view view_personel_ordered_by_name
				//rss=stmt.executeQuery("SELECT * from personel WHERE activity='1'");
				rss=stmt.executeQuery("SELECT * from view_personel_ordered_by_name");
				
				int counter=0;
				while(rss.next()){
					counter++;
					
				}
				
				if(counter>0){
					rss.first();
					personels= new Personnel[counter];
					int m=0;
					personels[m]=new Personnel();
					
					
					if(rss.getInt("personel_vehicle_id")==-1 || rss.getInt("personel_id")==vehicle.getVehicleDriverId() ){
						
							if(rss.getInt("personel_id")==vehicle.getVehicleDriverId()){
								vehicleDriverIndex=m+1;
							}
							driverIdField.addItem(rss.getString("personel_name"));
							personels[m].setPersonnelId(rss.getInt("personel_id"));
							personels[m].setPersonnelName(rss.getString("personel_name"));
							m++;
				}
				
			
					while(rss.next()){
						
						personels[m]=new Personnel();
						
						
						if(rss.getInt("personel_vehicle_id")==-1 || rss.getInt("personel_id")==vehicle.getVehicleDriverId() ){
							
								if(rss.getInt("personel_id")==vehicle.getVehicleDriverId()){
									vehicleDriverIndex=m+1;
								}
								driverIdField.addItem(rss.getString("personel_name"));
								personels[m].setPersonnelId(rss.getInt("personel_id"));
								personels[m].setPersonnelName(rss.getString("personel_name"));
								m++;
					}
						
					}
				}
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		   
		   driverIdField.setSelectedIndex(vehicleDriverIndex);
		   System.out.println("vehicleDriverIndex= "+vehicleDriverIndex);
		   driverIdField.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent event) {
					// TODO Auto-generated method stub
					

                  JComboBox comboBox = (JComboBox) event.getSource();
   
                  //
                  // Print the selected items and the action command.
                  //
                  Object selected = comboBox.getSelectedItem();
                  selectedDriverName=selected.toString();
                 
                  String command = event.getActionCommand();
                 
                  
                  int index= comboBox.getSelectedIndex();
                  if(index==0){
                	  driverId2=-1;
                  }
                  else{
                	  driverId2=index;
                  }
                  
                  if(selected.toString().equals("Personel Adı")){
                	  vehicleAvailability=1;
                  }
                  else{
                	  vehicleAvailability=0;
                  }
                
                  // '"+cidField.getText()+"'
                  
                  //
                  // Detect whether the action command is "comboBoxEdited"
                  // or "comboBoxChanged"
                  //
                  if ("comboBoxEdited".equals(command)) {
                      //System.out.println("User has typed a string in " +
                        //      "the combo box.");
                  } else if ("comboBoxChanged".equals(command)) {
                      //System.out.println("User has selected an item " +
                        //      "from the combo box.");
                  }
                  
                  if(index!=0){
                	  newDriverId= personels[index-1].getPersonnelId();
                  }
                  else{
                	  newDriverId=-1;
                  }
                 
                  
                  System.out.println("newDriverId: "+newDriverId+"  exDriverId: "+exDriverId);
				}
      		
      	});
		
		
		
		
	
		
		JLabel PhoneLabel = new JLabel("Kilometre");
		PhoneLabel.setBounds(305, 40, 90, 20);
		getContentPane().add(PhoneLabel);
		
		JButton lastMaintanenceDateButton = new JButton("Son Bakım");
		lastMaintanenceDateButton.setBounds(305, 10, 110, 20);
		lastMaintanenceDateButton.addActionListener(new ActionListener() {
	        public void actionPerformed(ActionEvent ae) {
	            lastMaintenanceField.setText(new DatePicker(VehicleEdition.this).setPickedDate());
	        }
	    });
		getContentPane().add(lastMaintanenceDateButton);
		
		lastMaintenanceField = new JTextField();
		lastMaintenanceField.setBounds(442, 11, 130, 20);
		lastMaintenanceField.setText(vehicle.getVehicleLastMaintenence());
		getContentPane().add(lastMaintenanceField);
		lastMaintenanceField.setColumns(10);
		
		kmField = new JTextField();
		kmField.setBounds(442, 41, 130, 20);
		kmField.setText(Integer.toString(vehicle.getVehicleKm()));
		getContentPane().add(kmField);
		kmField.setColumns(10);
		
		JButton address1Label = new JButton("Muayene");
		address1Label.setBounds(20, 70, 125, 20);
		address1Label.addActionListener(new ActionListener() {
	        public void actionPerformed(ActionEvent ae) {
	            	nextInspectionField.setText(new DatePicker(VehicleEdition.this).setPickedDate());
	        }
	    });
		getContentPane().add(address1Label);
		nextInspectionField = new JTextField();
		nextInspectionField.setBounds(157, 72, 130, 20);
		nextInspectionField.setText(vehicle.getVehicleNextInspection());
		getContentPane().add(nextInspectionField);
		nextInspectionField.setColumns(10);
		
		JButton adress2Label = new JButton("Sigorta Bitim");
		adress2Label.setBounds(305, 69, 125, 20);
		adress2Label.addActionListener(new ActionListener() {
	        public void actionPerformed(ActionEvent ae) {
	            insurenceEndDateField.setText(new DatePicker(VehicleEdition.this).setPickedDate());
	        }
	    });
		getContentPane().add(adress2Label);
		
		insurenceEndDateField = new JTextField();
		insurenceEndDateField.setBounds(442, 71, 130, 20);
		insurenceEndDateField.setText(vehicle.getVehicleInsuranceEndDate());
		getContentPane().add(insurenceEndDateField);
		insurenceEndDateField.setColumns(10);
		
		vehicleEditButton = new JButton("Düzenle");
		vehicleEditButton.setForeground(Color.BLACK);
		vehicleEditButton.setFont(new Font("Arial", Font.BOLD, 16));
		vehicleEditButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
			    
				
				
			//	driverId=driverIdField.getText();vehicleEditButton
				licencePlate=licencePlateField.getText();
				insurenceEndDate=insurenceEndDateField.getText();
				lastMaintenance=lastMaintenanceField.getText();
				nextInspection=nextInspectionField.getText();
				km=kmField.getText();
				//int driverId2=Integer.parseInt(driverId);
				int km2=Integer.parseInt(km);
				String insurenceEndDate2= insurenceEndDateField.getText().replaceAll("(\\d+)-(\\d+)-(\\d+)", "$3-$2-$1");
				String lastMaintenance2 = lastMaintenanceField.getText().replaceAll("(\\d+)-(\\d+)-(\\d+)", "$3-$2-$1");
				String nextInspection2 = nextInspectionField.getText().replaceAll("(\\d+)-(\\d+)-(\\d+)", "$3-$2-$1");
				
				if(driverId2==-1){
					newDriverId=-1;
				}
				
				
				String insert="UPDATE vehicle SET vehicle_driver_id='"+newDriverId+"'," +
						"vehicle_licence_plate='"+licencePlate+"',vehicle_insurance_enddate='"+insurenceEndDate2+"'," +
								"vehicle_last_maintenance='"+lastMaintenance2+"',vehicle_km='"+km2+"'," +
										"vehicle_next_inspection='"+nextInspection2+"',vehicle_availability='"+vehicleAvailability+"' " +
												"WHERE vehicle_id='"+vehicle.getVehicleId()+"'";
				
				
				
				
					System.out.println("Ready to execute sql");
				 	Connection con = null;
			        Statement st = null;
			        ResultSet rs = null;

			        String url = "jdbc:mysql://localhost:3306/mydb";
			        String user = "root";
			        String password = "qweasdzxc";

			        try {
			            con = (Connection) DriverManager.getConnection(url, user, password);
			            st = (Statement) con.createStatement();
			            st.executeUpdate(insert);
			            
			           
			            if(newDriverId!=exDriverId && newDriverId!=-1){
			            	st.executeUpdate("UPDATE personel set personel_vehicle_id=-1 WHERE personel_id='"+exDriverId+"'");
							st.executeUpdate("UPDATE personel set personel_vehicle_id='"+vehicle.getVehicleId()+"' WHERE personel_id='"+newDriverId+"'");	
							st.executeUpdate("UPDATE vehicle set vehicle_driver_id='"+newDriverId+"',vehicle_availability=0  WHERE vehicle_id='"+vehicle.getVehicleId()+"'");
						}
			            else if(newDriverId!=exDriverId){
			            	st.executeUpdate("UPDATE personel set personel_vehicle_id=-1 WHERE personel_id='"+exDriverId+"'");
							st.executeUpdate("UPDATE vehicle set vehicle_driver_id=-1,vehicle_availability=1  WHERE vehicle_id='"+vehicle.getVehicleId()+"'");
			            }
			            
			            
			            int messageType = JOptionPane.PLAIN_MESSAGE;
			          
			            JOptionPane.showMessageDialog(null, "Kayıt Alınmıştır", "Uyarı!!", messageType);
			            con.close();
			        } catch (SQLException ex) {
			            Logger lgr = Logger.getLogger(main.class.getName());
			            lgr.log(Level.SEVERE, ex.getMessage(), ex);

			        } finally {
			            try {
			                if (rs != null) {
			                    rs.close();
			                }
			                if (st != null) {
			                    st.close();
			                }
			                if (con != null) {
			                    con.close();
			                }

			            } catch (SQLException ex) {
			                Logger lgr = Logger.getLogger(main.class.getName());
			                lgr.log(Level.WARNING, ex.getMessage(), ex);
			            }
			        }
			        
			        // this will make sure WindowListener.windowClosing() et al. will be called.
			      //  WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
			        //Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);

			        // this will hide and dispose the frame, so that the application quits by
			        // itself if there is nothing else around. 
			        cti.addNewItem();
			        setVisible(false);
			        dispose();
			}});
		
		vehicleEditButton.setBounds(420, 134, 120, 25);
		getContentPane().add(vehicleEditButton);
		
		setVisible(true);  

		
	}
    
    
  
}
